package com.bjpowernode.seckillservice.listener;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.Orders;
import com.bjpowernode.seckillservice.service.OrderService;
import com.bjpowernode.seckillservice.service.impl.DelayMessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OrderListener {
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private DelayMessageService delayMessageService;

    @RabbitListener(queues = Constants.QUEUE_NAME_ORDER, concurrency = "6")
    public void onMessage(Message message, Channel channel) {
        long tag = message.getMessageProperties().getDeliveryTag();
        try {
            Orders orders = objectMapper.readValue(message.getBody(), Orders.class);
            int orderResult = orderService.doOrder(orders);
            if (orderResult == 1) {
                redisTemplate.opsForValue().set(Constants.REDIS_RESULT + orders.getGoodsId() + ":" + orders.getUid(), orders);
                channel.basicAck(tag, false);
                delayMessageService.sendDelayMessage(orders.getId());
                return;
            }
            channel.basicNack(tag, false, true);
        } catch (IOException e) {
            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
}